package com.example.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.example.common.CustomException;
import com.example.common.ServiceCode;
import com.example.common.ServiceException;
import com.example.dao.CartInfoDao;
import com.example.entity.CartInfo;
import com.example.entity.GoodsInfo;
import com.example.entity.Account;
import com.example.entity.UserInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CartInfoService {

    @Resource
    private CartInfoDao cartInfoDao;
    @Resource
    private GoodsInfoService goodsInfoService;
	@Resource
	private AdminInfoService adminInfoService;
	@Resource
	private UserInfoService userInfoService;

    //包装用户名和菜品名
    public void packCart(CartInfo cartInfo){
        Long userId = cartInfo.getUserId();
        Long goodsId = cartInfo.getGoodsId();
        GoodsInfo g = this.goodsInfoService.findById(goodsId);
        String name = g.getName();
        cartInfo.setGoodsName(name);
        UserInfo u = this.userInfoService.findById(userId);
        String name1 = u.getName();
        cartInfo.setUserName(name1);
        Integer level = u.getLevel();
        cartInfo.setLevel(level);
    }


    public List<GoodsInfo> findAll(Long userId, Integer level) {
        List<GoodsInfo> goodsList = new ArrayList<>();
        List<CartInfo> cartInfoList = cartInfoDao.findCartByUserId(userId, level);

        for (CartInfo cartInfo : cartInfoList) {
            Long goodsId = cartInfo.getGoodsId();
            GoodsInfo goods = goodsInfoService.findById(goodsId);
            if (goods != null) {
                // 注意这里返回的count是用户加入菜品的数量，而不是菜品的库存
                goods.setCount(cartInfo.getCount());
                // 这里返回的id也是购物车里菜品的关系id
                goods.setId(cartInfo.getGoodsId());
                goodsList.add(goods);
            }
            packCart(cartInfo);
        }
        return goodsList;
    }

    public PageInfo<CartInfo> findPageDetails(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Account user = (Account) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomException("1001", "session已失效，请重新登录");
        }
        Integer userLevel = user.getLevel();
        PageHelper.startPage(pageNum, pageSize);
        List<CartInfo> infoList;
        if (userLevel == 1) {
            infoList = cartInfoDao.findAll();
            // 处理一下userName
            for (CartInfo info : infoList) {
                Long userId = info.getUserId();
                Integer level = info.getLevel();
				if (level == 1) {
					info.setUserName(adminInfoService.findById(userId).getName());
				}
				if (level == 3) {
					info.setUserName(userInfoService.findById(userId).getName());
				}

            }
        } else {
            infoList = cartInfoDao.findCartByUserId(user.getId(), user.getLevel());
        }
        return PageInfo.of(infoList);
    }

    public CartInfo findById(Long id) {
        return cartInfoDao.selectByPrimaryKey(id);
    }


    //加入购物车
    public CartInfo add(CartInfo detailInfo) {
        Long userId = detailInfo.getUserId();
        Long goodsId = detailInfo.getGoodsId();
        // 先查询购物车里有没有该菜品，有就更新数量，没有就添加
        Example example = new Example(CartInfo.class);
        example.createCriteria()
                .andEqualTo("userId", userId)
                .andEqualTo("level", detailInfo.getLevel())
                .andEqualTo("goodsId", goodsId);
        List<CartInfo> infos = cartInfoDao.selectByExample(example);
        if (CollectionUtil.isEmpty(infos)) {
            // 新增
            //查询菜品
            GoodsInfo goods1 = this.goodsInfoService.findById(goodsId);
            //检查库存
            if (goods1.getCount() < detailInfo.getCount()){
                throw new ServiceException(ServiceCode.ERR_EXISTS, "商品库存不足");
            }
            detailInfo.setCreateTime(DateUtil.formatDateTime(new Date()));
            cartInfoDao.insertSelective(detailInfo);
        } else {
            // 更新数量
            CartInfo cartInfo = infos.get(0);
            //购物车菜品数量
            Integer count = detailInfo.getCount() + cartInfo.getCount();
            //查询菜品
            GoodsInfo goods1 = this.goodsInfoService.findById(goodsId);
            //检查库存
            if (goods1.getCount() < count){
                throw new ServiceException(ServiceCode.ERR_EXISTS, "商品库存不足");
            }
            cartInfo.setCount(count);
            cartInfoDao.updateByPrimaryKeySelective(cartInfo);
        }
        packCart(detailInfo);
        return detailInfo;
    }

    /**
     * 根据userid、goodsid和level定位购物车项并进行数目的修改
     * @param detailInfo
     * @return
     */
    public CartInfo updateCount(CartInfo detailInfo) {
        Long goodsId = detailInfo.getGoodsId();
        Long userId = detailInfo.getUserId();
        Integer level = detailInfo.getLevel();

        Integer count = detailInfo.getCount();
        GoodsInfo byId = this.goodsInfoService.findById(detailInfo.getGoodsId());
        //检查库存
        if (byId.getCount() < count){
            throw new ServiceException(ServiceCode.ERR_EXISTS, "菜品库存不足");
        }
        CartInfo cartInfo = this.cartInfoDao.selectByUserIdAndGoodsId(userId, goodsId, level);
        cartInfo.setCount(detailInfo.getCount());
        cartInfoDao.updateByPrimaryKeySelective(cartInfo);
        return cartInfo;
    }


    public void delete(Long id) {
        cartInfoDao.deleteByPrimaryKey(id);
    }

    public void empty(Long userId, Integer level) {
        cartInfoDao.deleteByUserId(userId, level);
    }

    public void deleteGoods(Long userId, Integer level, Long goodsId) {
        cartInfoDao.deleteGoods(userId, level, goodsId);
    }
}
